<template>
	<view class="uni-container">
		<uni-forms ref="form" :model="formData" validateTrigger="bind">
			<uni-forms-item name="category_id" label-width="100" label="商品类型" required>
				<!-- <uni-easyinput placeholder="分类 id，参考`opendb-mall-categories`表" v-model="formData.category_id"></uni-easyinput> -->
				<ljs-treeChoose-vue3 v-model="ljs_tree.treeData" :ids="ljs_tree.chooseIds" :props="ljs_tree.props"
					:keywordsFilter="true" :checkStrictly="true" @getChooseValue="ljs_treeGetChooseValue"
					:showAllLevels="false">
				</ljs-treeChoose-vue3>
			</uni-forms-item>
			<uni-forms-item name="user_id" label="文章作者">
				<uni-easyinput placeholder="文章作者名称" v-model="formData.user_id[0].username" disabled></uni-easyinput>
			</uni-forms-item>
<!-- 			<uni-forms-item name="category_id" label="分类">
				<uni-data-picker v-model="formData.category_id" collection="opendb-news-categories"
					field="name as text, _id as value"></uni-data-picker>
			</uni-forms-item> -->
			<uni-forms-item name="title" label="标题" required>
				<uni-easyinput placeholder="标题" v-model="formData.title" trim="both"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="content" label-width="100" label="文章内容" required>
				<!-- <uni-easyinput placeholder="文章内容" v-model="formData.content" trim="right"></uni-easyinput> -->
				<view id="wangeditor"></view>
			</uni-forms-item>
			<uni-forms-item name="excerpt" label="文章摘录">
				<uni-easyinput placeholder="文章摘录" v-model="formData.excerpt" trim="both"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="article_status" label="文章状态">
				<uni-data-checkbox v-model="formData.article_status"
					:localdata="formOptions.article_status_localdata"></uni-data-checkbox>
			</uni-forms-item>
			<uni-forms-item name="comment_status" label="开放评论">
				<uni-data-checkbox v-model="formData.comment_status"
					:localdata="formOptions.comment_status_localdata"></uni-data-checkbox>
			</uni-forms-item>
			<!--      <uni-forms-item name="last_comment_user_id" label="">
        <uni-easyinput placeholder="最后回复用户 id，参考`uni-id-users` 表" v-model="formData.last_comment_user_id"></uni-easyinput>
      </uni-forms-item> -->
			<uni-forms-item name="avatar" label="封面大图">
				<!-- <uni-easyinput placeholder="缩略图地址" v-model="formData.avatar" trim="both"></uni-easyinput> -->
				<button @click="chooseImage" size="mini">选择图片</button>
				<progress :percent="percent" show-info stroke-width="3" />
				<image v-if="formData.avatar" :src="formData.avatar" style="width: 100px; height: 100px;"></image>
			</uni-forms-item>
			<uni-forms-item name="publish_date" label="发表时间">
				<uni-datetime-picker return-type="timestamp" v-model="formData.publish_date"></uni-datetime-picker>
			</uni-forms-item>
			<uni-forms-item name="last_modify_date" label="最后修改时间">
				<uni-datetime-picker return-type="timestamp" v-model="formData.last_modify_date"></uni-datetime-picker>
			</uni-forms-item>
			<!--      <uni-forms-item name="mode" label="排版显示模式">
        <undefined v-model="formData.mode"></undefined>
      </uni-forms-item> -->
			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;">
					<button class="uni-button" style="width: 100px;">返回</button>
				</navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import {
		nextTick
	} from 'vue';
	import {
		validator
	} from '../../js_sdk/validator/opendb-news-articles.js';
	import E from 'wangeditor'
	let editor = null

	const dbCollectionName2 = "opendb-news-categories";

	const db = uniCloud.databaseForJQL();

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				result[key] = validator[key]
			}
		}
		return result
	}



	export default {
		data() {
			let formData = {
				"user_id": "",
				"category_id": "",
				"title": "",
				"content": "",
				"excerpt": "",
				"article_status": 0,
				"comment_status": 0,
				"last_comment_user_id": "",
				"avatar": "",
				"publish_date": null,
				"last_modify_date": null,
				"mode": null
			}
			return {
				percent: 0, //图片上传进度条
				ljs_tree: {
					treeData: [],
					chooseIds: [], // 选择tree的id数据结果集合
					props: {
						label: 'name',
						id: '_id',
						children: 'children'
					},
				},
				formData,
				formOptions: {
					"article_status_localdata": [{
							"value": 0,
							"text": "草稿箱"
						},
						{
							"value": 1,
							"text": "已发布"
						}
					],
					"comment_status_localdata": [{
							"value": 0,
							"text": "关闭"
						},
						{
							"value": 1,
							"text": "开放"
						}
					]
				},
				rules: {
					...getValidator(Object.keys(formData))
				}
			}
		},
		onLoad(e) {
			this.loadData()
			if (e.id) {
				const id = e.id
				this.formDataId = id
				this.getDetail(id).then((res)=>{
					// console.log(1111111111, res)
					editor.txt.html(res.content)
				})
			
			}
		},
		onReady() {
			this.initEditor() //编辑器初始化
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			/**
			 * 类别树展开
			 */
			loadData() {
				var that = this
				db.collection(dbCollectionName2)
					.field("sort,name,_id,parent_id")
					.orderBy("parent_id asc,sort asc")
					.get({
						getTree: true
					})
					.then((res) => {
						that.ljs_tree.treeData = res.data
						console.log("treeData", that.ljs_tree.treeData);
					}).catch((err) => {
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
					})
			},
			ljs_treeGetChooseValue(ids, items) {
				this.formData.category_id = ids[0]
				// console.log(ids,items)
				this.ljs_tree.chooseIds = ids;
			},
			chooseImage() {
				const _self = this
				uniCloud.chooseAndUploadFile({
					type: 'image',
					count: 1,
					onChooseFile(res) {
						return Promise.all(res.tempFiles).then((fileList) => {
							let result = {
								tempFilePaths: []
							}
							result.tempFiles = fileList.map((fileItem, index) => {
								result.tempFilePaths.push(fileItem.path)
								// console.log(222222222222222,fileItem)
								return {
									path: fileItem.path,
									cloudPath: '' + Date.now() + index + '.' + fileItem.name.split(
										'.')[1], // 云端路径，这里随便生成了一个
									fileType: fileItem.fileType
								}
							})
							return result
						})
					},
					onUploadProgress(progressEvent) {
						console.log(progressEvent);
						_self.percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
					}
				}).then(async (res) => {
					if (res && res.tempFiles && res.tempFiles.length > 0) {
						// 方式1：直接使用云存储返回的 URL（推荐）
						uni.showToast({
							icon: 'none',
							title: '上传成功',
							duration: 1500
						})
						this.formData.avatar = res.tempFiles[0].url
						console.log("上传的图片", this.formData.avatar)
					
						// 方式2：如果需要临时访问链接，使用文件ID
						// const tempUrlRes = await uniCloud.getTempFileURL({
						//     fileList: [res.tempFiles[0].fileID] // 注意：这里使用 fileID，不是 url
						// })
						// this.formData.avatar = tempUrlRes.fileList[0].tempFileURL
					}
				}).catch(err => {
					console.error('上传过程出错:', err)
					uni.showToast({
						icon: 'none',
						title: '上传失败',
						duration: 1500
					})
				})
			},
			initEditor() {
				editor = new E('#wangeditor')
				editor.config.zIndex = 0
				// 取消自动 focus
				editor.config.focus = false
				editor.config.onblur = function(newHtml) {
					console.log('onblur', newHtml) // 获取最新的 html 内容
				}
				editor.config.onfocus = function(newHtml) {
					console.log('onfocus', newHtml) // 获取最新的 html 内容
				}
				// 配置 onchange 回调函数
				const that = this
				editor.config.onchange = function(newHtml) {
					console.log("change 之后最新的 html", newHtml);
					that.formData.content = newHtml
				};
				// 配置触发 onchange 的时间频率，默认为 200ms
				editor.config.onchangeTimeout = 500; // 修改为 500ms

				// 本地上传图片
				editor.config.uploadImgMaxSize = 1 * 1024 * 1024 // 默认限制图片大小是 5M
				editor.config.uploadImgAccept = ['jpg', 'jpeg', 'png', 'gif', 'bmp',
					'webp'
				] // 默认['jpg', 'jpeg', 'png', 'gif', 'bmp']
				editor.config.customUploadImg = function(resultFiles, insertImgFn) {
					// resultFiles 是 input 中选中的文件列表
					// insertImgFn 是获取图片 url 后，插入到编辑器的方法
					resultFiles.forEach(async file => {
						let filePath = URL.createObjectURL(file)
						let cloudPath = file.name
						const result = await uniCloud.uploadFile({
							filePath,
							cloudPath
						});
						// 上传图片，返回结果，将图片插入到编辑器中
						// 腾讯云，支付宝云先使用getTempFileURL对fileID处理
						let temp = await uniCloud.getTempFileURL({
							fileList: [result.fileID]
						});
						temp.fileList.forEach((f) => {
							insertImgFn(f.tempFileURL)
						})
					})
				}
				editor.create()
			},
			/**
			 * 验证表单并提交
			 */
			submit() {
				uni.showLoading({
					mask: true
				})
				this.$refs.form.validate().then((res) => {
					// console.log(1111111111111, res)
					res.user_id = res.user_id[0]._id
					return this.submitForm(res)
				}).catch(() => {}).finally(() => {
					uni.hideLoading()
				})
			},

			/**
			 * 提交表单
			 */
			submitForm(value) {
				// 使用 clientDB 提交数据
				return db.collection("opendb-news-articles").doc(this.formDataId).update(value).then((res) => {
					uni.showToast({
						title: '修改成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			},

			/**
			 * 获取表单数据
			 * @param {Object} id
			 */
			async getDetail(id) {
				uni.showLoading({
					mask: true
				})
				try {
					const users = db.collection("uni-id-users").field("_id,nickname,username,mobile").getTemp()
					const res = await db.collection("opendb-news-articles",users).where("_id=='"+id+"'").field(
						"category_id,title,content,excerpt,article_status,comment_status,last_comment_user_id,avatar,publish_date,last_modify_date,mode,user_id._id,user_id.username,user_id.mobile"
					).get()
					// console.log(222222222222,res.data)
					const data = res.data[0]
					
					if (data) {
						this.formData = data
						//设置父类别
						this.ljs_tree.chooseIds = [this.formData.category_id]
						
						// console.log(11111,data,this.ljs_tree.chooseIds )
						uni.hideLoading()
						return data
					}
				} catch (error) {
					uni.showModal({
						content: error.message || '请求服务失败',
						showCancel: false
					})
				}
				
				
			}
		}
	}
</script>